package com.whmnx.main.ui.videorecord;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.tencent.qcloud.ugckit.UGCKitConstants;
import com.tencent.qcloud.ugckit.UGCKitVideoRecord;
import com.tencent.qcloud.ugckit.basic.UGCKitResult;
import com.tencent.qcloud.ugckit.component.dialogfragment.VideoWorkProgressFragment;
import com.tencent.qcloud.ugckit.module.effect.VideoEditerSDK;
import com.tencent.qcloud.ugckit.module.effect.bgm.TCMusicInfo;
import com.tencent.qcloud.ugckit.module.effect.bgm.TCMusicManager;
import com.tencent.qcloud.ugckit.module.effect.bgm.view.IEditMusicPannel;
import com.tencent.qcloud.ugckit.module.effect.bgm.view.TCEditMusicPannel;
import com.tencent.qcloud.ugckit.module.effect.utils.DraftEditer;
import com.tencent.qcloud.ugckit.module.record.MusicInfo;
import com.tencent.qcloud.ugckit.module.record.UGCKitRecordConfig;
import com.tencent.qcloud.ugckit.module.record.VideoRecordSDK;
import com.tencent.qcloud.ugckit.module.record.interfaces.IVideoRecordKit;
import com.tencent.qcloud.ugckit.module.upload.TXUGCPublish;
import com.tencent.qcloud.ugckit.module.upload.TXUGCPublishTypeDef;
import com.tencent.qcloud.ugckit.utils.BackgroundTasks;
import com.tencent.qcloud.ugckit.utils.DialogUtil;
import com.tencent.qcloud.ugckit.utils.ToastUtil;
import com.tencent.rtmp.TXLog;
import com.tencent.ugc.TXVideoEditer;
import com.whmnx.base.bean.BaseBean;
import com.whmnx.base.bean.MusicBean;
import com.whmnx.base.constants.Constants;
import com.whmnx.base.http.CallBack;
import com.whmnx.base.http.HttpClient;
import com.whmnx.base.utils.ImgVideoPickerUtils;
import com.whmnx.base.utils.MediaUtils;
import com.whmnx.base.view.RoundImageView;
import com.whmnx.main.R;
import com.whmnx.main.ui.adapter.MusicListAdapter;
import com.whmnx.main.ui.fragment.MyManagementFragment;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;
import me.goldze.mvvmhabit.utils.SPUtils;

/**
 * 小视频录制界面
 *
 */
public class TCVideoRecordActivity extends FragmentActivity implements ActivityCompat.OnRequestPermissionsResultCallback {

    private final String TAG = "TCVideoRecordActivity";

    public UGCKitVideoRecord mUGCKitVideoRecord;

    private Dialog dialogHead;

    private TXUGCPublish   mTXUGCPublish;

    private VideoWorkProgressFragment mWorkLoadingProgress;


    private boolean mIsCancelPublish;

    private String  mSignature;

    private String  mVideoPath;

    private VideoServerManager.PublishSigListener mPublishSigListener;
    private EditText mEditVideoTitle;
    private String mTitleStr;
    private TextView mTvShangPing;
    private List<MusicBean> musicList = new ArrayList<>();
    private TXVideoEditer editer;
    private String videoPath;

    private TCMusicManager.LoadMusicListener mLoadMusicListener;
    private MusicListAdapter musicListAdapter;
    private String path2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initWindowParam();

        // 必须在代码中设置主题(setTheme)或者在AndroidManifest中设置主题(android:theme)
        setTheme(R.style.RecordActivityTheme);

        setContentView(R.layout.activity_video_record);

        mUGCKitVideoRecord = (UGCKitVideoRecord) findViewById(R.id.video_record_layout);
        mTvShangPing =  findViewById(R.id.tv_shangPing);

        UGCKitRecordConfig ugcKitRecordConfig = UGCKitRecordConfig.getInstance();
        //基础设置
        mUGCKitVideoRecord.setConfig(ugcKitRecordConfig);


        mUGCKitVideoRecord.tvVideo.setOnClickListener(v -> {
            ImgVideoPickerUtils.openVideo(this);
        });


        mUGCKitVideoRecord.getTitleBar().setOnBackClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mUGCKitVideoRecord.setOnRecordListener(new IVideoRecordKit.OnRecordListener() {
            @Override
            public void onRecordCanceled() {
                finish();
            }

            @Override
            public void onRecordCompleted(UGCKitResult ugcKitResult) {  //// 录制完成回调
                if (ugcKitResult.errorCode == 0) {
                    //startEditActivity();
                    showFaduDialog(ugcKitResult.outputPath);
                } else {
                    ToastUtil.toastShortMessage("record video failed. error code:" + ugcKitResult.errorCode + ",desc msg:" + ugcKitResult.descMsg);
                }
            }
        });
        //添加音乐
        mUGCKitVideoRecord.setOnMusicChooseListener(position -> {
            // Intent bgmIntent = new Intent(TCVideoRecordActivity.this, TCMusicActivity.class);
            //  bgmIntent.putExtra(UGCKitConstants.MUSIC_POSITION, position);
            //  startActivityForResult(bgmIntent, UGCKitConstants.ACTIVITY_MUSIC_REQUEST_CODE);
            Dialog  dialogHead = new Dialog(TCVideoRecordActivity.this, R.style.ActionSheetDialogStyle);
            View view = LayoutInflater.from(TCVideoRecordActivity.this).inflate(R.layout.dialog_music, null);
            RecyclerView rlShop = view.findViewById(R.id.rl_shop);
            LinearLayoutManager layoutManager = new LinearLayoutManager(TCVideoRecordActivity.this);
            //配置布局，默认为vertical（垂直布局），下边这句将布局改为水平布局
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            rlShop.setLayoutManager(layoutManager);
            rlShop.setItemAnimator(new DefaultItemAnimator());
            musicListAdapter = new MusicListAdapter(TCVideoRecordActivity.this);
            rlShop.setAdapter(musicListAdapter);


            view.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialogHead.dismiss();
                }
            });

            dialogHead.setContentView(view);
            Window window = dialogHead.getWindow();
            if (window == null) {
                return;
            }
            //宽高最大
            window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
            //显示对话框//设置Dialog从窗体底部弹出
            dialogHead.setCanceledOnTouchOutside(true);
            dialogHead.show();
            window.setGravity(Gravity.BOTTOM);
            //获取窗体的属性
            WindowManager.LayoutParams lp = window.getAttributes();
            //设置Dialog距离底部的距离
            //将属性设置给窗体
            window.setAttributes(lp);

            Map<String, Object> params = new HashMap<>();
            params.put("search","");
            params.put("pageIndex",1);
            params.put("pageSize",10);
            HttpClient.post(TCVideoRecordActivity.this, Constants.MUSICLIST, params,new CallBack<List<MusicBean>>() {
                @Override
                public void onSuccess(List<MusicBean> musicBeans) {
                    musicList.clear();
                    musicList.addAll(musicBeans);
                    musicListAdapter.addAll(musicBeans);
                }
            });

            musicListAdapter.setOnClickSubItemListener(new MusicListAdapter.OnClickSubItemListener() {
                @Override
                public void onClickUseBtn(Button button, int position,String path) {
                    MusicBean musicInfo = musicList.get(position);
                    showMusicEdit(musicInfo,path);

                     // mUGCKitVideoRecord.setRecordMusicInfo(musicInfo);
                    //   dialogHead.dismiss();
                }
            });
        });

        initData();
        initListener();
    }

    /**
     * 弹出背景音乐修改
     * @param musicInfo
     * @param path
     */
    private void showMusicEdit(MusicBean musicInfo, String path) {
      //  MusicInfo musicInfo2 = new MusicInfo();
     //   musicInfo2.path = "/storage/emulated/0/Android/data/com.tencent.qcloud.xiaoshipin/files/bgm/测试音乐3";

     //   mUGCKitVideoRecord.setRecordMusicInfo(musicInfo2);

       DraftEditer mEditerDraft = DraftEditer.getInstance();
        MusicInfo  mMusicInfo = DraftEditer.getInstance().loadMusicInfo();

        Dialog  dialogHead = new Dialog(TCVideoRecordActivity.this, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(TCVideoRecordActivity.this).inflate(R.layout.ugckit_fragment_bgm, null);

        TCEditMusicPannel mTCEditMusicPannel = (TCEditMusicPannel) view.findViewById(com.tencent.qcloud.ugckit.R.id.tc_record_bgm_pannel);
        dialogHead.setContentView(view);
        Window window = dialogHead.getWindow();
        if (window == null) {
            return;
        }
        //宽高最大
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        //显示对话框//设置Dialog从窗体底部弹出
        dialogHead.setCanceledOnTouchOutside(true);
        dialogHead.show();
        window.setGravity(Gravity.BOTTOM);
        //获取窗体的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //设置Dialog距离底部的距离
        //将属性设置给窗体
        window.setAttributes(lp);


        editer = VideoEditerSDK.getInstance().getEditer();

        if (TextUtils.isEmpty(path)){
            dialogHead.dismiss();
            return;
        }
        int result = editer.setBGM(path);
        if (result != 0) {
            DialogUtil.showDialog(TCVideoRecordActivity.this, getResources().getString(com.tencent.qcloud.ugckit.R.string.ugckit_bgm_setting_fragment_video_edit_failed), getResources().getString(com.tencent.qcloud.ugckit.R.string.ugckit_bgm_setting_fragment_background_sound_only_supports_mp3_or_m4a_format), null);
        }
        try {
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
            mMusicInfo.duration = mediaPlayer.getDuration();
            mediaPlayer.release();
        } catch (IOException e) {
            e.printStackTrace();
        }
        editer.setBGMStartTime(0, mMusicInfo.duration);
        editer.setBGMVolume(0.5f);
        editer.setVideoVolume(0.5f);

        DraftEditer.getInstance().saveRecordMusicInfo(mMusicInfo);

        mMusicInfo.videoVolume = 0.5f;
        mMusicInfo.bgmVolume = 0.5f;
        mMusicInfo.startTime = 0;
        mMusicInfo.endTime = mMusicInfo.duration;
      //  mMusicInfo.path = path;

        //设置背景音乐
        mTCEditMusicPannel.setMusicInfo(mMusicInfo);
        //修改音乐
        mTCEditMusicPannel.setOnMusicChangeListener(new IEditMusicPannel.MusicChangeListener() {
            @Override
            public void onMicVolumeChanged(float volume) {
                mEditerDraft.setVideoVolume(volume);

                TXVideoEditer editer = VideoEditerSDK.getInstance().getEditer();
                editer.setVideoVolume(volume);
            }

            @Override
            public void onMusicVolumChanged(float volume) {
                mEditerDraft.setBgmVolume(volume);

                TXVideoEditer editer = VideoEditerSDK.getInstance().getEditer();
                editer.setBGMVolume(volume);
            }

            @Override
            public void onMusicTimeChanged(long startTime, long endTime) {
                mEditerDraft.setBgmStartTime(startTime);
                mEditerDraft.setBgmEndTime(endTime);

                // bgm 播放时间区间设置
                VideoEditerSDK.getInstance().getEditer().setBGMStartTime(startTime, endTime);
            }

            @Override
            public void onMusicReplace() {  //确定音乐
                mUGCKitVideoRecord.setRecordMusicInfo(mMusicInfo);
                dialogHead.dismiss();
            }

            @Override
            public void onMusicDelete() {  //删除
                mEditerDraft.setBgmPath(null);
                TXVideoEditer editer = VideoEditerSDK.getInstance().getEditer();
                editer.setBGM(null);
                dialogHead.dismiss();
            }
        });
    }

    private void downloadMusic(int position) {
        MusicBean musicInfo = musicList.get(position);
        TCMusicManager.getInstance().downloadMusicInfo(musicInfo.getMusic_Title(), position, Constants.HOST + musicInfo.getMusic_Url());
    }



    Disposable subscribe;
    private void initData() {
        mTXUGCPublish = new TXUGCPublish(this.getApplicationContext(), "customID");
        //商品管理
        mTvShangPing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int lv = SPUtils.getInstance().getInt(Constants.LV);
                if (lv != 2){
                    ToastUtil.toastShortMessage("请先去V2认证");
                    return;
                }
                startActivity(new Intent(TCVideoRecordActivity.this,MyManagementFragment.class));
            }
        });

        subscribe = RxBus.getDefault().toObservable(String.class)
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String object){
                        if (object.contains("time")){
                            UGCKitRecordConfig ugcKitRecordConfig = UGCKitRecordConfig.getInstance();
                            //基础设置
                            mUGCKitVideoRecord.setConfig(ugcKitRecordConfig);
                            //启动预览
                            //  TXUGCRecord txugcRecord = VideoRecordSDK.getInstance().getRecorder();
                            VideoRecordSDK.getInstance().stopCameraPreview();
                            // 打开录制预览界面
                            VideoRecordSDK.getInstance().startCameraPreview(mUGCKitVideoRecord.getRecordVideoView());

                          /*  TXRecordCommon.TXUGCSimpleConfig simpleConfig = new TXRecordCommon.TXUGCSimpleConfig();
                            simpleConfig.videoQuality = ugcKitRecordConfig.mQuality;
                            simpleConfig.minDuration = ugcKitRecordConfig.mMinDuration;
                            simpleConfig.maxDuration = ugcKitRecordConfig.mMaxDuration;
                            simpleConfig.isFront = ugcKitRecordConfig.mFrontCamera;
                            simpleConfig.touchFocus = ugcKitRecordConfig.mTouchFocus;
                            simpleConfig.needEdit = ugcKitRecordConfig.mIsNeedEdit;

                            txugcRecord.startCameraSimplePreview(simpleConfig, mUGCKitVideoRecord.getRecordVideoView());*/
                        }
                    }
                });
        RxSubscriptions.add(subscribe);
    }


    private void initWindowParam() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    private void startEditActivity() {
        // Intent intent = new Intent(this, TCVideoEditerActivity.class);
        //  startActivity(intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (hasPermission()) {
            mUGCKitVideoRecord.start();
        }
    }

    private boolean hasPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissions = new ArrayList<>();
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)) {
                permissions.add(Manifest.permission.CAMERA);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)) {
                permissions.add(Manifest.permission.RECORD_AUDIO);
            }
            if (permissions.size() != 0) {
                ActivityCompat.requestPermissions(this, permissions.toArray(new String[0]), 100);
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onStop() {
        super.onStop();
        mUGCKitVideoRecord.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUGCKitVideoRecord.release();
        RxSubscriptions.remove(subscribe);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mUGCKitVideoRecord.screenOrientationChange();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
      /*  if (requestCode != UGCKitConstants.ACTIVITY_MUSIC_REQUEST_CODE) {
            return;
        }*/
        if (data == null) {
            return;
        }

        if (requestCode == UGCKitConstants.ACTIVITY_MUSIC_REQUEST_CODE){
            MusicInfo musicInfo = new MusicInfo();

            musicInfo.path = data.getStringExtra(UGCKitConstants.MUSIC_PATH);
            musicInfo.name = data.getStringExtra(UGCKitConstants.MUSIC_NAME);
            musicInfo.position = data.getIntExtra(UGCKitConstants.MUSIC_POSITION, -1);

            mUGCKitVideoRecord.setRecordMusicInfo(musicInfo);

        }else {

            List<LocalMedia> mMediaList = PictureSelector.obtainMultipleResult(data);
            for (LocalMedia localMedia : mMediaList) {
                if (localMedia.getPictureType().equals("video/mp4")) {
                    videoPath = localMedia.getPath();
                    showFaduDialog(videoPath);
                    //  Bitmap videoThumb = MediaUtils.getVideoThumb(localMedia.getPath());
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        mUGCKitVideoRecord.backPressed();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults != null && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            mUGCKitVideoRecord.start();
        }
    }


    //回调
    private void initListener() {

        mPublishSigListener = new VideoServerManager.PublishSigListener() {
            @Override
            public void onSuccess(String signatureStr) {
                mSignature = signatureStr;
                publish();
            }

            @Override
            public void onFail(final int errCode) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mWorkLoadingProgress != null && mWorkLoadingProgress.isAdded()) {
                            mWorkLoadingProgress.dismiss();
                        }
                        Toast.makeText(TCVideoRecordActivity.this, "err code = " + errCode, Toast.LENGTH_SHORT).show();
                        //   startPlay();
                    }
                });
            }
        };
        VideoServerManager.getInstance().setPublishSigListener(mPublishSigListener);


        mLoadMusicListener = new TCMusicManager.LoadMusicListener() {
            @Override
            public void onBgmList(@Nullable final ArrayList<TCMusicInfo> tcBgmInfoList) {
                BackgroundTasks.getInstance().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }

            @Override
            public void onBgmDownloadSuccess(final int position, final String filePath) {
                Log.d(TAG, "onBgmDownloadSuccess filePath:" + filePath);
                try {
                    Thread.sleep(200);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                BackgroundTasks.getInstance().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        path2 = filePath;
                        MusicBean info = musicList.get(position);
                        musicListAdapter.updateItem(position, info);
                    }
                });
            }

            @Override
            public void onDownloadFail(final int position, final String errorMsg) {
                Log.d(TAG, "onDownloadFail errorMsg:" + errorMsg);
                BackgroundTasks.getInstance().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        ToastUtil.toastShortMessage(getResources().getString(com.tencent.qcloud.ugckit.R.string.ugckit_bgm_select_activity_download_failed));
                    }
                });
            }

            @Override
            public void onDownloadProgress(final int position, final int progress) {
                Log.d(TAG, "onDownloadProgress progress:" + progress);
                BackgroundTasks.getInstance().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }
        };
        TCMusicManager.getInstance().setOnLoadMusicListener(mLoadMusicListener);
    }

    /**
     * 上传回调
     */
    private void publish() {
        mTXUGCPublish.setListener(new TXUGCPublishTypeDef.ITXVideoPublishListener() {
            @Override
            public void onPublishProgress(long uploadBytes, long totalBytes) {
                TXLog.d(TAG, "onPublishProgress [" + uploadBytes + "/" + totalBytes + "]");
                if(mIsCancelPublish){
                    return;
                }
                mWorkLoadingProgress.setProgress((int) ((uploadBytes * 100) / totalBytes));
            }

            @Override
            public void onPublishComplete(TXUGCPublishTypeDef.TXPublishResult result) {
                TXLog.d(TAG, "onPublishComplete [" + result.retCode + "/" + (result.retCode == 0 ? result.videoURL : result.descMsg) + "]");
                if (mWorkLoadingProgress != null && mWorkLoadingProgress.isAdded()) {
                    mWorkLoadingProgress.dismiss();
                }

                if(mIsCancelPublish){
                    return;
                }


                // 注意：如果取消发送时，是取消的剩余未上传的分片发送，如果视频比较小，分片已经进入任务队列了是无法取消的。此时不跳转到下一个界面。
                if (result.retCode == TXUGCPublishTypeDef.PUBLISH_RESULT_OK) {
                    reportVideoInfo(result);
                } else {
                    if (result.descMsg.contains("java.net.UnknownHostException") || result.descMsg.contains("java.net.ConnectException")) {
                        Toast.makeText(TCVideoRecordActivity.this, getString(R.string.ugcupload_error_publish_without_network, result.descMsg), Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(TCVideoRecordActivity.this, getString(R.string.ugcupload_message_publish_fail,result.retCode, result.descMsg), Toast.LENGTH_SHORT).show();
                    }
                    //  startPlay();
                }
            }
        });

        TXUGCPublishTypeDef.TXPublishParam param = new TXUGCPublishTypeDef.TXPublishParam();
        // signature计算规则可参考 https://www.qcloud.com/document/product/266/9221
        param.signature = mSignature;
        param.videoPath = mVideoPath;
        //  param.coverPath = mCoverImagePath;
        mTitleStr = mEditVideoTitle.getText().toString();
        if(TextUtils.isEmpty(mTitleStr)){
            mTitleStr = "";
        }
        param.fileName = mTitleStr;
        //调用上传
        mTXUGCPublish.publishVideo(param);
    }


    /**
     * 上传到自己的服务器
     * @param result
     */
    private void reportVideoInfo(TXUGCPublishTypeDef.TXPublishResult result) {
        // VideoServerManager.getInstance().reportVideoInfo(result.videoId, "腾讯云");
        Map<String, Object> params = new HashMap<>();
        params.put("work_Title",mTitleStr);
        params.put("work_Image","");
        params.put("work_Vidoe",result.videoURL);
        params.put("work_UserInfoId", SPUtils.getInstance().getString(Constants.USERID));
        HttpClient.post(TCVideoRecordActivity.this, Constants.ADDWORK, params,new CallBack<BaseBean>() {
            @Override
            public void onSuccess(BaseBean result) {
                ToastUtil.toastLongMessage("发布成功");
                dialogHead.dismiss();
                finish();
            }
        });
    }


    //发布
    private void showFaduDialog(String outputPath) {
        mVideoPath = outputPath;
        dialogHead = new Dialog(this, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_fabu_video, null);

        mEditVideoTitle = view.findViewById(R.id.et);
        RoundImageView iv = view.findViewById(R.id.iv);
        //图片转换图片
        Bitmap videoThumb = MediaUtils.getVideoThumb(outputPath);
        iv.setImageBitmap(videoThumb);


        view.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogHead.dismiss();
            }
        });

        view.findViewById(R.id.bt_fabu).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mEditVideoTitle.getText().toString())){
                    ToastUtil.toastShortMessage("请输入发布内容");
                    return;
                }
                publishVideo(outputPath);
                dialogHead.dismiss();
            }
        });

        dialogHead.setContentView(view);
        Window window = dialogHead.getWindow();
        if (window == null) {
            return;
        }
        //宽高最大
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        //显示对话框//设置Dialog从窗体底部弹出
        dialogHead.show();
        window.setGravity(Gravity.BOTTOM);
        //获取窗体的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //设置Dialog距离底部的距离
        lp.y = 20;
        //将属性设置给窗体
        window.setAttributes(lp);
    }

    /**
     * 发布视频到腾讯云
     * @param outputPath
     */
    private void publishVideo(String outputPath) {
        //  stopPlay(false);
        if (mWorkLoadingProgress == null) {
            initWorkLoadingProgress();
        }
        mWorkLoadingProgress.setProgress(0);
        mWorkLoadingProgress.show(getSupportFragmentManager(), "progress_dialog");

        //    VideoServerManager.getInstance().getPublishSig();

        Map<String, Object> params = new HashMap<>();
        HttpClient.get(TCVideoRecordActivity.this, Constants.TXY_SIGNATURE, params,new CallBack<BaseBean>() {
            @Override
            public void onSuccess(BaseBean result) {
                if (result.getStatus() == 1){
                    mSignature = (String) result.getResult();
                    publish();
                }
            }
        });

        mIsCancelPublish = false;

    }




    private void initWorkLoadingProgress() {
        if (mWorkLoadingProgress == null) {
            mWorkLoadingProgress = VideoWorkProgressFragment.newInstance("发布中...");
            mWorkLoadingProgress.setOnClickStopListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mTXUGCPublish != null) {
                        mTXUGCPublish.canclePublish();
                        mIsCancelPublish = true;
                        mWorkLoadingProgress.setProgress(0);
                        mWorkLoadingProgress.dismiss();
                        //  startPlay();
                    }
                }
            });
        }
        mWorkLoadingProgress.setProgress(0);
    }



}